package com.xiaoyu.lanling.feature.chat.model.message

import `in`.srain.cube.request.JsonData
import android.text.TextUtils
import com.xiaoyu.base.image.ImageLoadInfo
import com.xiaoyu.base.utils.FileUtil
import com.xiaoyu.im.datamodel.AppMessage
import com.xiaoyu.lanling.common.Constant.MessageAttrsKey.FIRST_PICTURE
import com.xiaoyu.lanling.common.Constant.MessageAttrsKey.LOCAL_FIRST_PICTURE
import com.xiaoyu.lanling.common.Constant.MessageAttrsKey.THUMB_HEIGHT
import com.xiaoyu.lanling.common.Constant.MessageAttrsKey.THUMB_WIDTH
import com.xiaoyu.lanling.feature.chat.viewholder.ChatViewHolderManager

class ChatMessageSendVideoItem(message: AppMessage) : ChatMessageSendBaseItem(message) {

    var duration = 0
    var videoUrl: String? = null
    var firstPictureUrl: String? = null
    var width = 0
    var height = 0

    init {
        duration = message.payload.duration
        videoUrl = message.payload.localPathOrUrlForMedia
        val attrs: JsonData = message.payload.attrsCopy
        val thumbWidth: Int = attrs.optInt(THUMB_WIDTH)
        val thumbHeight: Int = attrs.optInt(THUMB_HEIGHT)
        val imageLoadInfo = ImageLoadInfo(thumbWidth, thumbHeight)
        width = ChatImageSizer.getImageWidth(imageLoadInfo)
        height = ChatImageSizer.getImageHeight(imageLoadInfo)
        firstPictureUrl = getFirstPicture(attrs)
    }

    override val childrenViewType: Int
        get() = ChatViewHolderManager.TYPE_SEND_VIDEO

    private fun getFirstPicture(attrs: JsonData): String? {
        val localFirstPicture: String = attrs.optString(LOCAL_FIRST_PICTURE)
        if (!TextUtils.isEmpty(localFirstPicture) && FileUtil.isFileExist(localFirstPicture)) {
            return localFirstPicture
        }
        val firstPicture: String = attrs.optString(FIRST_PICTURE)
        return if (!TextUtils.isEmpty(firstPicture)) {
            firstPicture
        } else null
    }
}